<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>数据管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col :span="3">
          <el-tooltip class="item" content="建议先下载模板" effect="dark"
                      placement="top-start">
            <el-button icon="el-icon-upload"
                       type="primary"
                       @click="uploadDialogVisible = true">
              上传实例
            </el-button>
          </el-tooltip>
        </el-col>
        <el-col :span="3">
          <el-button icon="el-icon-download" type="primary"
                     @click="downloadDialogVisible = true">
            下载模板
          </el-button>
        </el-col>
        <el-col :span="3">
          <el-tooltip class="item" content="目前仅支持excel导出" effect="dark"
                      placement="top-start">
            <el-button icon="el-icon-download" type="primary" @click="downloadInstances">
              批量导出
            </el-button>
          </el-tooltip>
        </el-col>
        <el-col :span="3">
          <el-button icon="el-icon-delete" type="danger" @click="deleteInstances">
            批量删除
          </el-button>
        </el-col>
      </el-row>

      <el-table ref="multipleInstanceTable"
                :data="treeList.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                border
                stripe style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column label="实例编号" prop="id"></el-table-column>
        <el-table-column label="实例名称" prop="name"></el-table-column>
        <el-table-column label="实例状态">
          <template v-slot="scope">
            <el-tag v-if="scope.row.computed" type="success">已计算</el-tag>
            <el-tag v-else type="info">未计算</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="info" @click="handleDetail(scope.row.id)">详情</el-button>
            <el-button type="danger" @click="deleteTree(scope.row.id)">删除</el-button>
            <el-button type="primary" @click="exportTree(scope.row.id)">导出</el-button>
            <el-button v-if="!scope.row.computed" type="success" @click="calculate(scope.row.id)">计算</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination :total="total" background
                     layout="prev, pager, next"
                     @current-change="changeInstanceTablePage">
      </el-pagination>
    </el-card>

    <el-dialog :visible.sync="dialogVisible" title="选择导出格式" width="50%">
      <el-select v-model="value" placeholder="请选择">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary">
          <el-link :href="'http://42.193.101.229:3000/file/' + this.value + '/?treeId=' + this.instanceId"
                   icon='el-icon-download'>导出</el-link>
        </el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="uploadDialogVisible" title="选择上传格式" width="50%">
      <el-select v-model="value" placeholder="请选择">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-upload :accept="acceptType" :action="uploadURL" :on-success="handleUploaded" class="upload">
        <el-button type="primary">点击上传</el-button>
        <div v-if="value === 'ExportTreeByJson'" slot="tip" class="el-upload__tip">支持上传Json文件</div>
        <div v-else slot="tip" class="el-upload__tip">支持上传Excel文件</div>
      </el-upload>
    </el-dialog>

    <el-dialog :visible.sync="downloadDialogVisible" title="下载模板" width="50%">
      <el-select v-model="value" placeholder="请选择">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="downloadDialogVisible = false">取 消</el-button>
        <el-button type="primary">
          <el-link :href="downloadURL" icon='el-icon-download'>下载模板</el-link>
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      treeList: [],
      total: 0,
      dialogVisible: false,
      uploadDialogVisible: false,
      downloadDialogVisible: false,
      instanceId: 0,
      value: '',
      options: [{
        value: 'ExportTreeByJson',
        label: 'JSON'
      }, {
        value: 'ExportTreeByExcel',
        label: 'Excel'
      }
      ],
      currentPage: 1,//当前页数
      pageSize: 10,//1p十个数据
      multipleInstanceSelection: []//这里处理多选的数据
    }
  },
  computed: {
    uploadURL() {
      if (this.value === 'ExportTreeByExcel') {
        return 'http://42.193.101.229:3000/file/ImportTreeByExcel?structId=' + this.$route.query.treeid
      } else {
        return 'http://42.193.101.229:3000/file/ImportTreeByJson?structId=' + this.$route.query.treeid
      }
    },
    downloadURL() {
      if (this.value === 'ExportTreeByExcel') {
        return 'http://42.193.101.229:3000/file/ExportTemplatesByExcel?treeId=' + this.$route.query.treeid
      } else {
        return 'http://42.193.101.229:3000/file/ExportTemplatesByJson?treeId=' + this.$route.query.treeid
      }
    },
    acceptType() {
      if (this.value === 'ExportTreeByExcel') {
        return ".xlsx, .xls"
      } else {
        return '.json'
      }
    }
  },
  created() {
    this.getAllTrees()
  },
  methods: {
    async getAllTrees() {
      const id = this.$route.query.treeid
      // 根据指标树id获取所有指标树
      const res = await this.$http.get(`data-tree/basic-info-under-tree?structId=${id}`)

      if (res.code !== 200) {
        return this.$message.error('获取实例列表失败')
      }

      this.treeList = res.data
      this.total = res.data.length
    },
    handleDetail(id) {
      this.$router.push(`instancedetial?treeid=${id}`)
    },
    /**
     *
     * @param {id} id 实例树编号
     */
    async calculate(id) {
      const res = await this.$http.post(`ope/calculate?id=${id}`);
      if (res.code !== 200) {
        return this.$message.error(res.message);
      }
      this.$message.success(res.message);
      await this.getAllTrees();
    },
    async deleteTree(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该实例, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      //如果用户确认删除，则返回字符串confirm  错误用catch捕获，返回字符串cancel
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')

      const res = await this.$http.post(`/data-tree/delete-whole-tree?treeId=${id}`)

      if (res.code !== 200) {
        return this.$message.error('删除指标树失败！')
      }

      this.$message.success('删除指标树成功，即将刷新网页')
      await this.getAllTrees();
    },
    exportTree(id) {
      this.dialogVisible = true
      this.instanceId = id
    },
    handleUploaded(res) {
      if (res.code !== 200) {
        return this.$message.error(res.message);
      }

      this.$message.success('上传成功!');

      this.getAllTrees();

      this.dialogVisible = false;//在这里立刻关掉
    },
    changeInstanceTablePage(currentPage) {
      this.currentPage = currentPage;
    },
    /**
     * 处理多选事件,这里动态处理id
     * @param value 这里是被选择的列值
     */
    handleSelectionChange(value) {
      this.multipleInstanceSelection = value;
    },
    async deleteInstances() {
      if (this.multipleInstanceSelection.length === 0) {
        return this.$message.info("还没有选择任何数据实例.");
      }
      const confirmResult = await this.$confirm(
          `此操作将永久删除${this.multipleInstanceSelection.length}个实例, 是否继续?`,
          '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err);
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除');
      }
      let treeId = [];//需要删除的ID
      for (let target of this.multipleInstanceSelection) {
        treeId.push(target.id);//只传ID即可
      }
      const res = await this.$http.post("/data-tree/delete-some", treeId);
      if (res.code !== 200) {
        return this.$message.error(res.message);
      }
      this.$message.success(res.message);
      await this.getAllTrees();
    },
    /**
     * 基于AXIOS和blob批量导出数据
     */
    downloadInstances() {
      if (this.multipleInstanceSelection.length === 0) {
        return this.$message.error("还未选择导出的数据");
      }
      const url = "http://localhost:3000/file/exportInstances";
      let treeId = [];//需要导出的实例ID
      for (let target of this.multipleInstanceSelection) {
        treeId.push(target.id);//只传ID即可
      }
      axios({
        method: "post",
        url: url,
        data: treeId,
        responseType: 'blob'
      }).then(res => {
        let data = res.data;
        if (!data) {
          return;
        }
        let url = window.URL.createObjectURL(new Blob([data]))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', 'excel.xls')
        document.body.appendChild(link)
        link.click() //执行下载
        window.URL.revokeObjectURL(link.href) //释放url
        document.body.removeChild(link) //释放标签
      }).catch(err => err);
    }
  }
}
</script>

<style>
.upload {
  margin: 20px 0;
}
</style>